// 这是课程管理里面的分页和删除编辑的js
// 渲染课程表格
function renderCourseTable(data, currentPage = 1) {
    const tbody = document.getElementById('002').querySelector('tbody');
    tbody.innerHTML = '';
    
    const pageSize = 10; // 每页显示10条
    const start = (currentPage - 1) * pageSize;
    const end = start + pageSize;
    const pageData = data.slice(start, end);

    pageData.forEach((course, index) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${start + index + 1}</td>
            <td>${course.cname}</td>
            <td>${course.cprice || '免费'}</td>
            <td>${course.cstatus}</td>
            <td>${course.creleasetime}</td>
            <td>
                <button class="edit-btn" data-id="${course.id}">编辑</button>
                <button class="delete-btn" data-id="${course.id}">删除</button>
            </td>
        `;
        tbody.appendChild(row);
    });

    // 更新分页
    updatePagination(data.length, currentPage, pageSize);

    // 添加编辑和删除按钮的事件监听
    addButtonListeners();
}

// 添加按钮事件监听器
function addButtonListeners() {
    // 删除按钮事件
    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const courseId = this.dataset.id;
            if (confirm('确定要删除这个课程吗？')) {
                deleteCourse(courseId);
            }
        });
    });

    // 编辑按钮事件
    document.querySelectorAll('.edit-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const courseId = this.dataset.id;
            editCourse(courseId);
        });
    });
}

// 删除课程
function deleteCourse(courseId) {
    const params = new URLSearchParams({
        method: 'deletecourse',
        id: courseId
    });

    fetch(config.coursesip, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('删除成功！');
            // 重新加载课程列表
            searchCourses('', '', '');
        } else {
            alert('删除失败：' + (data.msg || '未知错误'));
        }
    })
    .catch(error => {
        console.error('删除课程失败:', error);
        alert('删除失败，请稍后重试');
    });
}

// 编辑课程
function editCourse(courseId) {
    const params = new URLSearchParams({
        method: 'updatecourse',
        id: courseId
        // 添加其他需要更新的字段
    });

    fetch(config.coursesip, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('编辑成功！');
            // 重新加载课程列表
            searchCourses('', '', '');
        } else {
            alert('编辑失败：' + (data.msg || '未知错误'));
        }
    })
    .catch(error => {
        console.error('编辑课程失败:', error);
        alert('编辑失败，请稍后重试');
    });
}

// 更新分页
function updatePagination(total, currentPage, pageSize) {
    const totalPages = Math.ceil(total / pageSize);
    const paginationDiv = document.querySelector('.pagination');
    paginationDiv.innerHTML = '';

    // 上一页
    const prevLink = document.createElement('a');
    prevLink.href = '#';
    prevLink.className = 'prev' + (currentPage === 1 ? ' disabled' : '');
    prevLink.textContent = '上一页';
    prevLink.addEventListener('click', (e) => {
        e.preventDefault();
        if (currentPage > 1) {
            searchCourses('', '', '', currentPage - 1);
        }
    });
    paginationDiv.appendChild(prevLink);

    // 页码
    for (let i = 1; i <= totalPages; i++) {
        const pageLink = document.createElement('a');
        pageLink.href = '#';
        pageLink.className = 'page' + (i === currentPage ? ' active' : '');
        pageLink.textContent = i;
        pageLink.addEventListener('click', (e) => {
            e.preventDefault();
            searchCourses('', '', '', i);
        });
        paginationDiv.appendChild(pageLink);
    }

    // 下一页
    const nextLink = document.createElement('a');
    nextLink.href = '#';
    nextLink.className = 'next' + (currentPage === totalPages ? ' disabled' : '');
    nextLink.textContent = '下一页';
    nextLink.addEventListener('click', (e) => {
        e.preventDefault();
        if (currentPage < totalPages) {
            searchCourses('', '', '', currentPage + 1);
        }
    });
    paginationDiv.appendChild(nextLink);

    // 更新总条数显示
    const totalCountSpan = document.querySelector('.total-count span');
    if (totalCountSpan) {
        totalCountSpan.textContent = total;
    }
}